<?php
declare(strict_types=1);
 

namespace App\Fastapp\Mapper;

use App\Fastapp\Model\AccountInviteLevel;
use App\Fastapp\Model\AccountWalletLog;
use App\Fastapp\Model\FastappChannel;
use App\Fastapp\Model\FastappChannelAgent;
use Hyperf\Database\Model\Builder;
use Mine\Abstracts\AbstractMapper;

/**
 * 钱包流水Mapper类
 */
class FastappAccountWalletLogMapper extends AbstractMapper
{
    /**
     * @var AccountWalletLog
     */
    public $model;

    public function assignModel()
    {
        $this->model = AccountWalletLog::class;
    }

    /**
     * 搜索处理器
     * @param Builder $query
     * @param array $params
     * @return Builder
     */
    public function handleSearch(Builder $query, array $params): Builder
    {
        // 用户id
        if (isset($params['user_id']) && filled($params['user_id'])) {
            $query->where('account_wallet_log.user_id', '=', $params['user_id']);
        }

        // 币种id
        if (isset($params['currency_id']) && filled($params['currency_id'])) {
            $query->where('currency_id', '=', $params['currency_id']);
        }

        // 1充值
        if (isset($params['type']) && filled($params['type'])) {
            $query->where('type', '=', $params['type']);
        }

        // 账户字段
        if (isset($params['field']) && filled($params['field'])) {
            $query->where('field', '=', $params['field']);
        }

        // 数据类型
        if (isset($params['object_type']) && filled($params['object_type'])) {
            $query->where('object_type', '=', $params['object_type']);
        }

        $query->selectRaw('account_wallet_log.*');
        $admin_id = user()->getId();
        if (!user()->isAdminRole() && $admin_id != env('SUPER_ADMIN')) {
            $roles = array_column(user()->getUserRole(), 'code');
            if (in_array('channel', $roles)) $query->where('channel', FastappChannel::query()->where(['admin_id' => $admin_id])->value('id'));
            else if (in_array('agent', $roles)) {
                $agent_user_id = FastappChannelAgent::query()->where(['admin_id' => $admin_id])->value('user_id');
                if (!$agent_user_id) return $query->whereRaw('1=0');
                $link = AccountInviteLevel::query()->where(['user_id' => $agent_user_id])->value('link');
                if ($link) $link .= '.' . $agent_user_id . '%'; else  $link = $agent_user_id . '|%';
                $query->join('account_invite_level as b', 'account_wallet_log.user_id', '=', 'b.user_id')->where('link', 'like', $link);
            } else $query->where('id', 0);
        }
        return $query->orderByDesc('account_wallet_log.id');
    }
}